package com.xiaoniu.lib_keleim.pojo.vos;

import com.xiaoniu.lib_keleim.ConversationType;
import com.xiaoniu.lib_keleim.utils.GsonUtil;
import com.xiaoniu.lib_keleim.utils.ProtocolField;

import java.lang.reflect.Field;

public class AckMessage {
    @ProtocolField(index = 1)
    public long messageId;
    //发送人用户ID
    @ProtocolField(index = 2)
    public String userId;
    //目标
    @ProtocolField(index = 3)
    public String targetId;
    //会话类型 聊天室:0 私聊 :1
    @ProtocolField(index = 4)
    public byte conversationType;
    //0,确认接收 已读
    @ProtocolField(index = 5)
    public Byte ackType;

    public static AckMessage obtainReceived(String targetId,ConversationType conversationType){
        return obtain(null,targetId, conversationType);
    }

    public static AckMessage obtainRead(Byte ackType,String targetId,ConversationType conversationType){
        return obtain(ackType,targetId, conversationType);
    }

    public static AckMessage obtain(Byte ackType,String targetId, ConversationType conversationType){
        AckMessage message = new AckMessage();
        message.userId = String.valueOf(UserInfoVO.getSingleton().getCustomerId());
        message.targetId = targetId;
        message.ackType = ackType;
        message.conversationType = (byte) conversationType.getValue();
        return message;
    }

    public String getRawData(){
        return GsonUtil.toJson(this);
    }

    public byte[] toBytes(AckMessage ackMessage) {
        StringBuilder data = new StringBuilder();

        Field[] declaredFields = getClass().getDeclaredFields();
        for (int i = 0; i < declaredFields.length; i++) {
            Field field = declaredFields[i];
            ProtocolField annotation = field.getAnnotation(ProtocolField.class);
            if (annotation!=null) {
                try {
                    data.append(String.format("@%s %s", annotation.index(),field.get(ackMessage)));
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }

        data.insert(0,">");
        data.insert(0,"~");

        data.append("<");
        data.append("~");
        return data.toString().getBytes();
    }
}
